<template xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
  <el-tabs type="card">
<!--    1. 商品分类      --------------------------------------------------->
    <el-tab-pane label="商品分类">
      <span slot="label"><i class="el-icon-s-opportunity"></i>商品基本信息</span>
      {{dataForm}}
      <el-form :inline="true" :model="dataForm" ref="dataForm" label-width="180px">
        <el-form-item label="商品分类:">
          <el-select v-model="dataForm.goods.category1Id" placeholder="请选择一级分类">
            <el-option
              v-for="item in categorys1"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category2Id" placeholder="请选择二级级分类">
            <el-option
              v-for="item in categorys2"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-select v-model="dataForm.goods.category3Id" placeholder="请选择三级分类">
            <el-option
              v-for="item in categorys3"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <span>模块:{{dataForm.goods.typeTemplateId}}</span>
        </el-form-item>
        <el-form-item label="商品名称:" style="width: 100%">
          <el-input v-model="dataForm.goods.goodsName" style="width:330%" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="品牌:" style="width: 100%">
          <el-select v-model="dataForm.goods.brandId" style="width: 310%" placeholder="请选择品牌">
            <el-option
              v-for="item in brands"
              :key="item.id"
              :label="item.text"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="副标题:" style="width: 100%">
          <el-input v-model="dataForm.goods.caption" style="width:330%" placeholder="请输入副标题"></el-input>
        </el-form-item>
        <!--        价格-->
        <el-form-item label="价格:" style="width: 100%">
          <el-input v-model="dataForm.goods.price" style="width:330%" placeholder="请输入价格"></el-input>
        </el-form-item>
        <el-form-item label="商品介绍:" style="width: 100%">
          <el-input type="textarea" v-model="dataForm.goodsDesc.introduction" style="width:325%"
                    placeholder="请输入商品介绍"></el-input>
        </el-form-item>
        <el-form-item label="包装列表:" style="width: 100%; ">
          <el-input type="textarea" v-model="dataForm.goodsDesc.packageList" style="width:325%"
                    placeholder="请输入包装列表"></el-input>
        </el-form-item>
        <el-form-item label="售后服务:" style="width: 100%">
          <el-input type="textarea" v-model="dataForm.goodsDesc.saleService" style="width:325%"
                    placeholder="请输入售后服务"></el-input>
        </el-form-item>
      </el-form>
    </el-tab-pane>
    <!--    2. 商品图片     --------------------------------------------------->
    <el-tab-pane label="商品图片">
      <el-button  size="small" @click="newUpload">新建</el-button>
     <span style="float: right"> {{dataForm.goodsDesc.itemImages}}</span>
      <el-table
        :data="dataForm.goodsDesc.itemImages"
        style="width: 100%;">
        <el-table-column
          prop="color"
          header-align="center"
          align="center"
          label="颜色">
        </el-table-column>
        <el-table-column
          header-align="center"
          align="center"
          label="图片">
          <template slot-scope="scope">
            <img :src="scope.row.url" width="100px" height="50px">
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          width="150"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="dataForm.goodsDesc.itemImages.splice(scope.$index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog title="商品图片上传" :visible.sync="dialogFormVisible">
          {{image}}
        <el-form :model="image">
          <el-form-item label="图片颜色" label-width="100px">
            <el-input v-model="image.color" ></el-input>
          </el-form-item>
          <el-form-item label="商品图片" label-width="100px">
            <!--:http-request="uploadFile" 此代码代表自定义文件上传-->
            <el-upload
              action=""
              class="upload-demo"
              :file-list="fileList"
              :http-request="uploadFile"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>

          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="closeUpload">确 定</el-button>
        </div>
      </el-dialog>
    </el-tab-pane>
    <!--    3. 扩展属性     --------------------------------------------------->
    <el-tab-pane label="扩展属性">
      {{dataForm.goodsDesc.customAttributeItems}}
      <el-table
        :data="dataForm.goodsDesc.customAttributeItems"
        style="width: 100%;"
        border>
        <el-table-column
          align="center"
          width="150px"
          >
          <template slot-scope="scope">
              {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column >
          <template slot-scope="scope" >
            <el-input v-model="scope.row.value" ></el-input>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <!--    4. 规格     --------------------------------------------------->
    <el-tab-pane label="规格">
<!--      4.1 规格选项多选框-->
      {{dataForm.goodsDesc.specificationItems}}
      <el-table
        :data ="specList"
        style="width: 100%;">
        <el-table-column width="150px">
          <template slot-scope="scope" >
            {{scope.row.text}}
          </template>
        </el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-checkbox-group v-model="optionList[scope.$index]" >
              <el-checkbox  @change="getOptionList" :label="option.optionName"  :key="option.id"   v-for="option in scope.row.options"></el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
<!--        4.2 规格选项列表 -->
      </el-table>
      <el-table
        :data="dataForm.items"
        style="width: 100%">
        <el-table-column
          width="200px"
          align="center"
          :key="key"
          :label="spec.attributeName"
          v-for="(spec,key) in dataForm.goodsDesc.specificationItems">
          <template slot-scope="scope">
            {{scope.row.spec[spec.attributeName]}}
          </template>
        </el-table-column>
        <!--2.2 处理价格-->
        <el-table-column  label="价格"  align="center" >
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"/>
          </template>
        </el-table-column>
        <!--2.3 处理数量-->
        <el-table-column  label="数量"  align="center" >
          <template slot-scope="scope">
            <el-input  v-model="scope.row.num"/>
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-button type="success" plain @click="save">保存</el-button>
    <el-button type="warning" plain>返回列表</el-button>
  </el-tabs>
</template>
<script>
  export default {
    data() {
      return {
        dataForm: {goods: {typeTemplateId: ''}, goodsDesc: {itemImages:[],customAttributeItems:[],specificationItems:[]}, items: []},
        categorys1: [],           //一级类目列表
        categorys2: [],           //二级类目列表
        categorys3: [],           //三级类目列表
        brands: [],               //根据模块id查出来的品牌列表
        fileList: [],             //提交文件的数组
        image: {},                //图片对象
        dialogFormVisible:false,  //是否显示上传图片对话框
        optionList:[],
        specList : [],
        specNames:[],             //查询出来的规格名称
      };

    },
    created() {
      //1. 查询一级目录列表
      this.findCategorys1();
      //2. 根据修改页面传入的id值得到商品对象
      this.findGoodsById();
    },
    methods: {
      save(){
        let id = this.$route.query.id;
        //1. 将需要添加的数据转换为json串
        this.dataForm.goodsDesc.specificationItems = JSON.stringify(this.dataForm.goodsDesc.specificationItems)
        this.dataForm.goodsDesc.itemImages = JSON.stringify(this.dataForm.goodsDesc.itemImages);
        this.dataForm.goodsDesc.customAttributeItems = JSON.stringify(this.dataForm.goodsDesc.customAttributeItems)
        //2. 转换this.dataForm.items中的每一个spec对象为字会串
        this.dataForm.items.forEach(item=>{
          item.spec = JSON.stringify(item.spec);
        })
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/${id?'update':'save'}`),
          method: `${id?'put':'post'}`,
          data:this.dataForm
        }).then(({data}) => {
          if (data && data.code === 0) {
            //1. 添加成功后将所有数据恢复成默认值
            // this.dataForm.goods = {};
            // this.dataForm.goodsDesc = {customAttributeItems: [],specificationItems: [],itemImages: []};
            // this.dataForm.items = [];
            this.dataForm={goods:{typeTemplateId:''},goodsDesc:{itemImages:[],customAttributeItems:[],specificationItems:[]},items:[]},
              this.specificationItems = []
            this.fileList = []
            this.optionList=[];   //选择的规格选项列表
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      //修改商品，数据回显
      findGoodsById(){
        //1. 拿到路由路径中传过来的id
        let id =  this.$route.query.id
        console.log("ID = ", id)
        //2. 根据传入的商品id，从后台查询出spu商品、spu商品描述、sku商品列表
        this.$http({
          url: this.$http.adornUrl(`/shop/goods/findGoodsById/${id}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log("findGoodsById:",data);
            this.dataForm = data.goods;
            this.dataForm.goods.brandId = parseInt(data.goods.goods.brandId);   //要将原来的字符串转换为整数
            //将json串转换为json对象(一定要在监听模板id时，判断是否有查询参数id，如果没有才执行从模板表得到自定义扩展属性)
            this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.goods.goodsDesc.customAttributeItems);
            this.dataForm.goodsDesc.itemImages = JSON.parse(data.goods.goodsDesc.itemImages);
            this.dataForm.goodsDesc.specificationItems = JSON.parse(data.goods.goodsDesc.specificationItems);
            this.dataForm.items.forEach(item=>{
              item.spec = JSON.parse(item.spec);
            })
            //为this.optionList赋值，就会自动选中
            let items = this.dataForm.goodsDesc.specificationItems
            this.optionList=[]
            for(let i = 0;i < items.length;i++){
              this.optionList[i]=items[i].attributeValue;
            }
            console.log("optionList--->",this.optionList);
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 1.点击规格选项复选框，触发的函数
      getOptionList(){
        console.log("optionList" , this.optionList )
        //1.1 定义一个数组
        let specList = [];
        //1.2 遍历所有规格选项
        for (let i = 0; i <this.optionList.length; i++) {
          //绑定规格选项集合和对应的规格名称
          let option = this.optionList[i];
          specList.push({attributeName:this.specNames[i],attributeValue:option});
        }
        //1.3 赋值给 this.dataForm.goodsDesc.specificationItems ,整合到dataForm对象中，便于添加
        this.dataForm.goodsDesc.specificationItems = specList;
        //1.4 处理特殊情况，如果该对象中的规格选项没有选的时候，删除掉
        this.dataForm.goodsDesc.specificationItems = this.dataForm.goodsDesc.specificationItems .filter(s=>{
          //只保留规格选项列表长度 > 0的 spec
          return s.attributeValue.length > 0;
        })
        //1.5  根据用户选择规格生成规格sku商品列表
        this.createItemList();
      },
      //2. 根据用户选择规格生成规格sku商品列表
      createItemList(){
        //2.1 定义默认的sku商品列表
        this.dataForm.items = [{spec:{},price:0,num:9999,status:'0',isDefault:'0'}];
        //2.2 拿到用户选择的规格列表
        let items = this.dataForm.goodsDesc.specificationItems;
        //2.3 判断这个列表是否为空，不为空遍历这个列表
        if(items && items.length >0){
          items.forEach(i=>{
            //2.4 调用 createColumn（）函数，定义生成的新的sku列表数组,赋值给dataForm.items
            this.dataForm.items = this.createColumn(this.dataForm.items,i.attributeName,i.attributeValue);
          })
        }
      },
      //3. 成的新的sku列表数组
      createColumn(items,specName,specValue){
        //3.1 定义生成的新的sku列表数组
        let skuList = [];
        //3.2 遍历传入的集合
        items.forEach(i=>{
          specValue.forEach(v=>{
              //① 根据旧行克隆出新行
              let newRow = JSON.parse(JSON.stringify(i))
              //② 为新行赋值
              newRow.spec[specName] = v;
              //③ 将新行添加到新的sku数组
              skuList.push(newRow);
          })
        })
        //3.3 返回新的sku数组
        return skuList;
      },
      //4. 查找所有一级分类
      findCategorys1() {
        let id = 0;
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${id}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys1 = data.list;
          }
        })
      },
      //2. 新建一个图片的上传
      newUpload(){
        //1. 显示对话框
        this.dialogFormVisible  = true;
        //2. 清空图片对象内容
        this.image = {};
        //3. 清空表格
        this.fileList = [];
      },
      //3. 自定义图片上传
      uploadFile(v){
        console.log(v.file)
        //3.1 组织需要上穿的数据
        let form = new FormData();
        //3.2 添加文件到form对象属性中
        form.append("file",v.file);
        //3.3 清空列表
        //3.4 开始上传
        this.$http({
          url: this.$http.adornUrl('/shop/upload/'),
          method: 'post',
          data: form,
          headers:{'Content-Type':'multipart/form-data'},
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.fileList.push({name:v.raw,url:data.url})
            this.image.url = data.url;
          }
        })

      },
      //4. 确定文件上传
      closeUpload(){
        console.log(this.image)
        //4.1 关闭对话框
        this.dialogFormVisible = false;
        //4.2
        this.dataForm.goodsDesc.itemImages.push(this.image)
      },
    },
    watch: { //观察
      //1. 当一级类目值发生变化时,自动查询出二级类目
      category1IdNew(id, oldId) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${id}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys2 = data.list;
          }
        })
      },
      category2IdNew(id, oldId) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/findByParentId/${id}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categorys3 = data.list;
          }
        })
      },
      category3IdNew(id, oldId) {
        this.$http({
          url: this.$http.adornUrl(`/shop/itemcat/info/${id}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataForm.goods.typeTemplateId = data.itemCat.typeId
          }
        })
      },
      //4. 模板id发生变化时，要做三件事
      //4.1 根据模板id查出品牌
      //4.2 根据模板id对应的扩展属性
      //4.3 查出模板表中的规格，并查出对应的规格选项
      typeTemplateIdNew(id, odlTypeId) {
        this.$http({
          url: this.$http.adornUrl(`/shop/typetemplate/info/${id}`),
          method: 'get',
        }).then(({data}) => {
          if (data && data.code === 0) {
            console.log(data.typeTemplate)
            //1. 查询品牌
            this.brands = JSON.parse(data.typeTemplate.brandIds)
            //2. 查询扩展属性
            if(this.$route.query.id){
              this.dataForm.goodsDesc.customAttributeItems = JSON.parse(data.typeTemplate.customAttributeItems)
            }
            //3. 查询出规格与规格选项
            this.$http({
              url: this.$http.adornUrl(`/shop/specification/findSpecList/${id}`),
              method: 'get',
            }).then(({data}) => {
              console.log(data)
              //4. 得到规格及对应的所有规格选项
             this.specList =  data.list;
              //5. 为规格选项列表赋值(这里一定要在修改商品id不存在时【即添加商品时】，这样设置optionList的值)
              if(this.$route.query.id){
                this.optionList = [];
                data.list.forEach(s=>{
                  //5.1 将规格选项按规格分成一个个对应的数组
                  this.optionList.push([]);
                })

              }
              //6. 遍历这个集合，将规格名称存入到specNames的数组中
              data.list.forEach(s=>{
                this.specNames.push(s.text)
              })
            })
          }
        })
      }
    },
    computed: {   //计算
      //1. 计算category1Id属性值
      category1IdNew() {
        return this.dataForm.goods.category1Id;
      },
      //2. 计算category2Id属性值
      category2IdNew() {
        return this.dataForm.goods.category2Id;
      },
      //3. 计算category3Id属性值
      category3IdNew() {
        return this.dataForm.goods.category3Id;
      },
      //4. 计算模板id的值
      typeTemplateIdNew() {
        return this.dataForm.goods.typeTemplateId;
      }

    }
  };
</script>
